package myJs

import myJs.Utils.{g, _}
import myJs.implicits.Implicits._
import myJs.myPkg.Implicits._
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.myPkg._
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, Event, window}
import scalatags.Text.all.s

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}


/**
 * Created by yz on 11/5/2020
 */
@JSExportTopLevel("Home")
object Home {

  val tableId = "table"

  @JSExport("init")
  def init = {
    refreshKeyword.map { x =>

    }
    bootStrapValidator

  }

  def refreshKeyword = {
    val url = g.jsRoutes.controllers.SearchController.getAllGeneSymbols().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      val data = JSON.parse(xhr.responseText).toJArS
      Tool.getInputByName("keyword").typeahead("destroy").typeahead(TypeaheadOptions.source(data)
        .highlighter(Tool.highlighterF).updater(Tool.updater).matcher(Tool.matcher))
    }
  }

  @JSExport("keywordSearch")
  def keywordSearch = {
    val formId = "form"
    $(s"#${formId}").bootstrapValidator("revalidateField", "keyword")
    val bv = jQuery(s"#${formId}").data("bootstrapValidator")
    bv.validate()
    val valid = bv.isValid().toB
    if (valid) {
      val index = layer.alert(Tool.loadingElement, Tool.layerOptions)
      val url = g.jsRoutes.controllers.SearchController.searchResultBefore().url.toString
      val keywords = Tool.getInputByName("keyword").`val`().toString.split(",")
      layer.close(index)
      if (keywords.size > 10) {
        Swal.swal(SwalOptions.title("Error").text("gene symbol is too many(must less than 10)!").`type`("error"))
      } else {
        window.location.href = s"${url}?keyword=${keywords.mkString(",")}"
      }

    }
  }

  def bootStrapValidator = {
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "keyword" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "keyword is required！"
            ),
          )
        ),
      )
    )
    g.$("#form").bootstrapValidator(dict)
  }

}
